package com.smartlight.godlight;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.smartlight.godlight.constant.GodlApi;
import com.smartlight.godlight.model.OrderInfo;
import com.smartlight.godlight.utils.OkHttpUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class Payment extends AppCompatActivity {
    private String TAG = "Payment";
    private OrderInfo orderInfo;
    private ImageView paycode;

    private Timer timer;

    @Override
    protected void  onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.payment);

        // 初始化定时器
        timer = new Timer();

        // toolbar
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        // 获取ActionBar对象（实际上是Toolbar）并设置属性
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true); // 显示返回箭头
            actionBar.setHomeAsUpIndicator(R.drawable.close_orange); // 设置返回图标
            actionBar.setTitle("取消订单"); // 设置标题文字
        }

        Button btn_godsubmit = findViewById(R.id.checkpayresult);
        paycode = findViewById(R.id.paycode);

        // 获取参数
        Intent intent = getIntent();
        orderInfo = intent.getParcelableExtra("orderInfo");
        Log.d(TAG, "---接收确定的订单信息----" + orderInfo.toString());

        Map<String,String> params = new HashMap<>();
        params.put("merOrderId", orderInfo.getOrderNo());
        if (GodlApi.isProd)
            params.put("totalAmount", orderInfo.getMoney() + "");
        else
            params.put("totalAmount", "1");

        Log.d(TAG, "--支付链接接口参数----" + params.toString());


        // 请求支付链接
        OkHttpUtils.post(GodlApi.GET_PAY_URL, params, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.d(TAG, "-支付链接接口失败----" + e.toString());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String result = response.body().string();
                Log.d(TAG, "-支付链接接口成功----" + result);
                JsonObject jsonObject = new Gson().fromJson(result, JsonObject.class);
                String payUrl = jsonObject.get("data").getAsJsonObject().get("payurl").getAsString();
                Log.d(TAG, "-支付链接接口成功----" + payUrl);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Bitmap bitmap = generateQRCodeBitmap(payUrl, 300, 300); // 生成二维码图片
                        paycode.setImageBitmap(bitmap); // 将图片设置到ImageView中
                    }
                });

            }
        });

        btn_godsubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                queryOrder();
            }
        });

        // 每隔2秒请求一次订单查询接口
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d(TAG, "查询订单是否支付成功");
                        // 支付成功后，取消定时器，并跳转页面去点亮佛灯
                        queryOrder();
                    }
                });
            }
        };

        // 开启定时器
        timer.schedule(timerTask, 1, 8000);
    }

    private void queryOrder(){
        Map<String,String> params = new HashMap<>();
        params.put("merOrderId", orderInfo.getOrderNo());
        // 查询支付结果
        OkHttpUtils.post(GodlApi.PAY_QUERY, params, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {

            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String result = response.body().string();
                Log.d(TAG, "---查询订单接口成功----" + result);

                try {
                    JsonObject jsonObject = new Gson().fromJson(result, JsonObject.class);

                    if (jsonObject.get("errCode").getAsString().equals("SUCCESS") && jsonObject.get("status").getAsString().equals("TRADE_SUCCESS")){
                        // 清除定时器
                        timer.cancel();
                        Intent intent = new Intent();
                        intent.setClass(Payment.this, PayRusult.class);
                        intent.putExtra("orderInfo", orderInfo);
                        startActivity(intent);
                    }
                } catch (Exception e) {
                    // add code here
                }
            }
        });
    }

    private Bitmap generateQRCodeBitmap(String text, int width, int height) {
        QRCodeWriter writer = new QRCodeWriter();
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); // 设置纠错等级为L（最低）
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 设置编码格式为UTF-8
        try {
            BitMatrix bitMatrix = writer.encode(text, BarcodeFormat.QR_CODE, width, height, hints);
            int[] pixels = new int[width * height];
            for (int y = 0; y < height; y++) {
                int offset = y * width;
                for (int x = 0; x < width; x++) {
                    pixels[offset + x] = bitMatrix.get(x, y) ? getResources().getColor(R.color.black) : getResources().getColor(R.color.white); // 根据二维码的黑白设置颜色值
                }
            }
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
            return bitmap;
        } catch (WriterException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 定时调订单支付查询接口，若检测支付成功，立即跳转，或者手动点击跳转



    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:

                // 创建一个AlertDialog.Builder对象
                AlertDialog.Builder builder = new AlertDialog.Builder(this);

                // 设置对话框的标题和消息
                builder.setTitle("温馨提示")
                        .setMessage("确定取消当前订单吗")
                        .setIcon(android.R.drawable.ic_dialog_info) // 设置图标（可选）
                        .setCancelable(false) // 设置是否可以通过点击返回键或点击对话框外取消对话框
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(Payment.this, MainActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                                finish();
                            }
                        });

                // 创建并显示对话框
                AlertDialog dialog = builder.create();
                dialog.show();

                return true; // 表示事件已被处理，不再向上传递
        }
        return super.onOptionsItemSelected(item); // 对于其他菜单项，调用父类的处理方法
    }

}
